#!/usr/bin/env python3
"""
启动WebRTC测试程序的便捷脚本
"""

import os
import sys
import subprocess
import time
import webbrowser
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 7):
        print("❌ 错误: 需要Python 3.7或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"✅ Python版本检查通过: {sys.version}")
    return True

def check_virtual_env():
    """检查虚拟环境"""
    venv_path = Path("venv")
    if not venv_path.exists():
        print("❌ 未找到虚拟环境，正在创建...")
        try:
            subprocess.run([sys.executable, "-m", "venv", "venv"], check=True)
            print("✅ 虚拟环境创建成功")
        except subprocess.CalledProcessError as e:
            print(f"❌ 创建虚拟环境失败: {e}")
            return False
    else:
        print("✅ 找到虚拟环境")
    return True

def get_pip_command():
    """获取pip命令路径"""
    if os.name == 'nt':  # Windows
        return str(Path("venv") / "Scripts" / "pip")
    else:  # Unix/Linux/macOS
        return str(Path("venv") / "bin" / "pip")

def get_python_command():
    """获取Python命令路径"""
    if os.name == 'nt':  # Windows
        return str(Path("venv") / "Scripts" / "python")
    else:  # Unix/Linux/macOS
        return str(Path("venv") / "bin" / "python")

def install_dependencies():
    """安装依赖包"""
    print("📦 正在安装依赖包...")
    pip_cmd = get_pip_command()
    
    try:
        # 升级pip
        subprocess.run([pip_cmd, "install", "--upgrade", "pip"], check=True)
        print("✅ pip升级成功")
        
        # 安装依赖
        if Path("requirements.txt").exists():
            subprocess.run([pip_cmd, "install", "-r", "requirements.txt"], check=True)
            print("✅ 依赖包安装成功")
        else:
            # 手动安装核心依赖
            packages = [
                "aiortc==1.6.0",
                "aiohttp==3.9.1", 
                "aiohttp-cors==0.7.0",
                "opencv-python==4.8.1.78",
                "numpy==1.24.3"
            ]
            for package in packages:
                print(f"安装 {package}...")
                subprocess.run([pip_cmd, "install", package], check=True)
            print("✅ 核心依赖包安装成功")
            
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装依赖包失败: {e}")
        print("请手动运行以下命令:")
        print(f"{pip_cmd} install -r requirements.txt")
        return False
    
    return True

def start_server():
    """启动WebRTC服务器"""
    print("🚀 正在启动WebRTC测试服务器...")
    python_cmd = get_python_command()
    
    try:
        # 启动服务器（非阻塞）
        process = subprocess.Popen(
            [python_cmd, "webrtc_server.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 等待服务器启动
        print("⏳ 等待服务器启动...")
        time.sleep(3)
        
        # 检查进程是否还在运行
        if process.poll() is None:
            print("✅ 服务器启动成功!")
            print("📡 服务器地址: http://localhost:8080")
            print("🔌 WebSocket地址: ws://localhost:8080/ws")
            print("📊 统计信息: http://localhost:8080/stats")
            
            # 自动打开浏览器
            try:
                webbrowser.open('http://localhost:8080')
                print("🌐 已自动打开浏览器")
            except:
                print("⚠️ 无法自动打开浏览器，请手动访问 http://localhost:8080")
            
            print("\n" + "="*50)
            print("🎯 WebRTC测试程序使用说明:")
            print("1. 在浏览器中点击'连接服务器'按钮")
            print("2. 点击'开始WebRTC测试'开始测试")
            print("3. 观察日志输出，查看连接过程")
            print("4. 如果看到绿色的✅状态，说明连接成功")
            print("5. 按Ctrl+C停止服务器")
            print("="*50)
            
            # 等待用户中断
            try:
                process.wait()
            except KeyboardInterrupt:
                print("\n🛑 正在停止服务器...")
                process.terminate()
                process.wait()
                print("✅ 服务器已停止")
        else:
            # 获取错误信息
            stdout, stderr = process.communicate()
            print(f"❌ 服务器启动失败")
            if stderr:
                print(f"错误信息: {stderr}")
            if stdout:
                print(f"输出信息: {stdout}")
            return False
            
    except Exception as e:
        print(f"❌ 启动服务器时出错: {e}")
        return False
    
    return True

def main():
    """主函数"""
    print("🌐 WebRTC测试程序启动器")
    print("="*40)
    
    # 检查Python版本
    if not check_python_version():
        return 1
    
    # 检查虚拟环境
    if not check_virtual_env():
        return 1
    
    # 安装依赖
    if not install_dependencies():
        return 1
    
    # 启动服务器
    if not start_server():
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main())